React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.<h1> tag is returned as JavaScript function to the render function.React.createElement() function returns an object:ReactDOM.render():render() method or it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:React.createElement() function tree:``jsx harmony function Greeting({ message }) { return <h1>{Hello, ${message}`}</h1>``jsx harmony class Greeting extends React.Component { render() { return <h1>{Hello, ${this.props.message}`}</h1> } }React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won't compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.this.props.reactProp inside component's render() method.reactProp property:setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.setState()?setState() is asynchronous the callback function is used for any post action.false to prevent default behavior:preventDefault() explicitly:() Whereas in react you should not append () with the function name. (refer "activateLasers" function in the first point for example).bind() or public class fields syntax approach considering performance.SyntheticEvent is a cross-browser wrapper around the browser's native event. It's API is same as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.&&.key is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.li tag.key prop is not present on list items.React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property within constructor.findDOMNode() API. Because findDOMNode() prevents certain improvements in React in the future.findDOMNode:ref attribute is a string, like ref={'textInput'}, and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have below issues, and are considered legacy. String refs were removed in React v16.this.refs, as well as its type (which could be different). Callback refs are friendlier to static analysis.name input is accessed using ref.React.createElement() functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it new props.constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods.setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods.componentWillUnmount() lifecycle method.getSnapshotBeforeUpdate().componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.shouldComponentUpdate() which returns true.render() and is invoked on every render. This exists for rare use cases where you need derived state. Worth reading if you need derived state.true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop.componentDidUpdate(). This is useful to capture information from the DOM i.e. scroll position.shouldComponentUpdate() returns false.this.props.children) that allow you to pass components as data to other components, just like any other prop you use. Component tree put between component's opening and closing tag will be passed to that component as children prop.React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray.this reference until super() method has been called. The same applies for ES6 sub-classes as well. The main reason of passing props parameter to super() call is to access this.props in your child constructors.this.props is different only within the constructor. It would be the same outside the constructor.React.lazy function supports default exports only. If you would like to import modules which are named exports, you can create an intermediate module that reexports it as the default. It also ensures that tree shaking keeps working and don’t pull unused components. Let's take a component file which exports multiple named components,MoreComponents.js components in an intermediate file IntermediateComponent.jsclassName over class attribute?class is a keyword in JavaScript, and JSX is an extension of JavaScript. That's the principal reason why React uses className instead of class. Pass a string as the className prop.this keyword altogether.constructor.isRequired.PropTypes.numberPropTypes.stringPropTypes.arrayPropTypes.objectPropTypes.funcPropTypes.nodePropTypes.elementPropTypes.boolPropTypes.symbolPropTypes.anypropTypes for User component as below:componentDidCatch(error, info) or static getDerivedStateFromError():unstable_handleError method. It has been renamed to componentDidCatch in React v16.React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.react-dom package?react-dom package provides DOM-specific methods that can be used at the top level of your app. Most of the components are not required to use this module. Some of the methods of this package are:render()hydrate()unmountComponentAtNode()findDOMNode()createPortal()react-dom?ReactDOMServer object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:renderToString()renderToStaticMarkup()renderToString to render your root component to a string, which you then send as response.dangerouslySetInnerHTML attribute is React's replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.dangerouslySetInnerHTML attribute for setting HTML markup:style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.node.style.backgroundImage).setState() in constructor?setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get error like this: Can only update a mounted or mounting component. So we need to use this.state to initialize variables inside constructor.setState() in componentWillMount() method?setState() inside componentWillMount() method. But at the same it is recommended to avoid async initialization in componentWillMount() lifecycle method. componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method. We need to make sure async calls for component initialization happened in componentDidMount() instead of componentWillMount().``jsx harmony componentDidMount() { axios.get(api/todos`) .then((result) => { this.setState({ messages: [...result.data] }) }) }false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true....rest operator, so it will add only required props.moize library can memoize the component in another component.DefinePlugin method to set NODE_ENV to production, by which it strip out things like propType validation and extra warnings. Apart from this, if you minify the code, for example, Uglify's dead-code elimination to strip out development only code and comments, it will drastically reduce the size of your bundle.create-react-app CLI tool allows you to quickly create & run React applications with no configuration step.constructor()static getDerivedStateFromProps()render()componentDidMount()componentWillMount()componentWillReceiveProps()componentWillUpdate()UNSAFE_ prefix, and the unprefixed version will be removed in React v17.getDerivedStateFromProps() lifecycle method?getDerivedStateFromProps() lifecycle method is invoked after a component is instantiated as well as before it is re-rendered. It can return an object to update state, or null to indicate that the new props do not require any state updates.componentDidUpdate() covers all the use cases of componentWillReceiveProps().getSnapshotBeforeUpdate() lifecycle method?getSnapshotBeforeUpdate() lifecycle method is called right before DOM updates. The return value from this method will be passed as the third parameter to componentDidUpdate().componentDidUpdate() covers all the use cases of componentWillUpdate().displayName.displayName for naming component:static methodsconstructor()getChildContext()componentWillMount()componentDidMount()componentWillReceiveProps()shouldComponentUpdate()componentWillUpdate()componentDidUpdate()componentWillUnmount()onClickSubmit() or onChangeDescription()getSelectReason() or getFooterContent()renderNavigation() or renderProfilePicture()render()page prop:setState() is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState() is called. That means you should not rely on the current state when calling setState() since you can't be sure what that state will be. The solution is to pass a function to setState(), with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState().setState(), the count gets incremented correctly.setState()?setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.setState() with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.React.StrictMode is a useful component for highlighting potential problems in an application. Just like <Fragment>, <StrictMode> does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for development mode only.<ComponentOne> and <ComponentTwo> components only.PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:isMounted() an anti-pattern and what is the proper solution?isMounted() is to avoid calling setState() after a component has been unmounted, because it will emit a warning.isMounted() before calling setState() does eliminate the warning, but it also defeats the purpose of the warning. Using isMounted() is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.setState() might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount(), prior to unmounting.onPointerDownonPointerMoveonPointerUponPointerCancelonGotPointerCaptureonLostPointerCaptureonPointerEnteronPointerLeaveonPointerOveronPointerOutgetInitialState() method when using React.createClass().React.createClass():React.createClass() is deprecated and removed in React v16. Use plain JavaScript classes instead.render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().forceUpdate() and only read from this.props and this.state in render().super() and super(props) in React using ES6 classes?this.props in constructor() then you should pass props to super() method.super(props):super():constructor() both will display same value for this.props.Array.prototype.map with ES6 arrow function syntax.items array of objects is mapped into an array of components:do expressions which are stage 1 proposal.``jsx harmony <img className='image' src={images/${this.props.image}`} />React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The react-dom package contains ReactDOM.render(), and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.react and react-dom. This paves the way to writing components that can be shared between the web version of React and React Native.<label> element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.resize event in componentDidMount() and then update the dimensions (width and height). You should remove the listener in componentWillUnmount() method.setState() and replaceState() methods?setState() the current and previous states are merged. replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason. You can also set state to false/null in setState() instead of using replaceState().componentDidUpdate lifecycle method will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.componentWillUpdate(object nextProps, object nextState) for state changes. It has been deprecated in latest releases.Array.prototype.filter() method.removeItem() method for updating the state.undefined won't work.<pre> tag so that the formatting of the JSON.stringify() is retained:input element and using it in componentDidMount():setState() with an object to merge with state:Object.assign() to create a copy of the object:setState() with a function:React.version to get the version.create-react-app?core-js:polyfills.js and import it into root index.js file. Run npm install core-js or yarn add core-js and import your specific required features.index.html:Array.prototype.includes feature as it is not included in the default feature set.HTTPS=true configuration. You can edit your package.json scripts section:set HTTPS=true && npm start.env in the project root and write the import path:src/app without relative paths.history object to record each page view:setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.static field to define constant.HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.async/await in React, you will need Babel and transform-async-to-generator plugin. React Native ships with Babel and a set of transforms.eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.eslint-plugin-jsx-a11y, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with alt text and tabindex, for example, will not be picked up by regular plugins.fetch. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved.history library which handles interaction with the browser's window.history with its browser and hash histories. It also provides memory history which is useful for environments that don't have global history, such as mobile app development (React Native) and unit testing with Node.<Router> components of React Router v4?<Router> components:<BrowserRouter><HashRouter><MemoryRouter>history instance associated with your router available through the context in the router object.push() and replace() methods of history?push()replace()push() will add a new location to the array and replace() will replace the current location in the array with the new one.withRouter() higher-order function:withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context.<Route> component and render props pattern:<Route> component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.URLSearchParams if you want something native:<Switch> block because <Switch> is unique in that it renders a route exclusively.Switch to your imports:<Switch> block:history.push method in React Router v4?history object:search property is used to pass query params in push() method.<Switch> renders the first child <Route> that matches. A <Route> with no path always matches. So you just need to simply drop path attribute as belowhistory object and import this module across the project.history.js file:<Router> component instead of built-in routers. Imported the above history.js inside index.js file:history object similar to built-in history object:react-router package provides <Redirect> component in React Router. Rendering a <Redirect> will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.<FormattedMessage> as placeholder using React Intl?<Formatted... /> components from react-intl return elements, not plain text, so they can't be used for placeholders, alt text, etc. In that case, you should use lower level API formatMessage(). You can inject the intl object into your component using injectIntl() higher-order component and then format the message using formatMessage() available on that object.injectIntl():injectIntl() higher-order component will give you access to the formatDate() method via the props in your component. The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date.TestRenderer package in React?jsdom.with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing.jsdom environment. It's often used for testing components.jsdom) so that your tests can be run on the command line.sum.js file:sum.test.js which contains actual test:package.json:yarn test or npm test and Jest will print a result:redux-immutable-state-invariant, Immutable.js, or instructing your team to write non-mutating code.mapStateToProps() and mapDispatchToProps()?mapStateToProps() is a utility which helps your component get updated state (which is updated by some other components):mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state):mapDispatchToPropscreateStore(). Also, it shouldn't pollute the global window object.componentDidMount() method and in render() method you can verify the data.connect() from React Redux?mapStateToProps(): It maps the state variables from your store to the props that you specify.mapStateToProps function is connected to the container. You can import connect() from react-redux.combineReducers().rootReducer() to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action.redux-persist, you may also need to clean your storage. redux-persist keeps a copy of your state in a storage engine. First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.at symbol in the Redux connect decorator?redux-thunk middleware which allows you to define async actions.connect() function, that creates a new component that wraps around your existing one. This pattern is called Higher-Order Components, and is generally the preferred way of extending a component's functionality in React. This allows you to map state and action creators to your component, and have them passed in automatically as your store updates.<FilterLink> component using connect:connect() over accessing the store directly (using context API).ReferenceError immediately.constants.js or actionTypes.js).actions.js:reducer.js:mapDispatchToProps()?dispatch() in mapDispatchToProps().ownProps parameter in mapStateToProps() and mapDispatchToProps()?ownProps parameter is specified, React Redux will pass the props that were passed to the component into your connect functions. So, if you use a connected component:redux-saga is a library that aims to make side effects (asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal Redux actions, it has access to the full Redux application state and it can dispatch Redux actions as well.call() and put() in redux-saga?call() and put() are effect creator functions. call() function is used to create effect description, which instructs middleware to call the promise. put() function creates an effect, which instructs middleware to dispatch an action to the store.dispatch() and getState() as parameters.redux-saga and redux-thunk?persistState() store enhancer, you can persist debug sessions across page reloads.applyMiddleware().redux-thunk and logger passing them as arguments to applyMiddleware():console.log, console.warn, etc. As of React Native v0.29 you can simply run the following to see logs in the console:Command + D and a webpage should open up at http://localhost:8081/debugger-ui.Command + Option + I to open the Chrome Developer tools, or open it via View -> Developer -> Developer Tools.null, unlike most type systems.font-awesome:font-awesome in your index.js file:className:file://...) then you must first open Chrome Extensions and check Allow access to file URLs.index.html of your React application:__REACT_DEVTOOLS_GLOBAL_HOOK__, then React communicates with that hook during initialization. If the website is not using React or if React fails to communicate with DevTools then it won't show up the tab.styled-components is a JavaScript library for styling React applications. It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript.<Title> and <Wrapper> components with specific styles for each.Title and Wrapper, are now components that you can render just like any other react component.create-react-app application?create-react-app now supports typescript natively. You can just pass --typescript option as below--scripts-version option as react-scripts-ts while you create a new project. react-scripts-ts is a set of adjustments to take the standard create-react-app project pipeline and bring TypeScript into the mix.statics only works with React.createClass():initialValues get updated from state?enableReinitialize : true setting.initialValues prop gets updated, your form will update too.oneOfType() method of PropTypes.string or number type as below:[email protected] and higher.React.lazy function lets you render an dynamic import as a regular component. It will automatically load the bundle containing the OtherComponent when the component gets rendered. This must return a Promise which resolves to a module with a default export containing a React component.<BrowserRouter>) which wraps specific child router components(<Route>).<BrowserRouter> component.render() method is the only required method in a class component. i.e, All methods other than render method are optional for a class component.<div/> and user defined elements.setState() in componentWillUnmount() because once a component instance is unmounted, it will never be mounted again.{name} which is short for {name: name})setState() calls as below,this.setState({comments}) updates only comments variable without modifying or replacing posts variable.Formik is a form library for react which provides solutions such as validation, keeping track of the visited fields, and handling form submission.Vaadin date picker web component as below,.bind(this) with in constructor for event handlers.React.createElement(component, props, ...children).select and textArea inputs. But you need to use defaultChecked for checkbox and radio inputs.top 10 websites using React as their front-end framework,useEffect is used to fetch the data with axios from the API and to set the data in the local state of the component with the state hook’s update function.useState?useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.Redux Thunk, Redux Promise, Redux Saga.react-scripts package is a set of scripts from the create-react-app starter pack which helps you kick off projects without configuring. The react-scripts start command sets up the development environment and starts a server, as well as hot module reloading.ReactDOMServer#renderToNodeStream method is used to generate HTML on the server and send the markup down on the initial request for faster page loads. It also helps search engines to crawl your pages easily for SEO purposes. Note: Remember this method is not available in the browser but only server.<a href> and create a security hole.<Provider> passing the store to React components